﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Xml;
using System.Text;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Ccit.Utils;
using Newtonsoft.Json;
using System.Collections.Generic;
using Microsoft.Web.UI.WebControls;

namespace Ccit.OA.Email
{
    public partial class email_wbyj_tree : Ccit.Utils.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ViewState["YJJXH"] = (null != Request.QueryString["YJJXH"]) ? Request.QueryString["YJJXH"].ToString() : "";
                ViewState["ctrlid"] = (null != Request.QueryString["ctrlid"]) ? Request.QueryString["ctrlid"].ToString() : "";
                ViewState["ctrlname"] = (null != Request.QueryString["ctrlname"]) ? Request.QueryString["ctrlname"].ToString() : "";
                ViewState["selType"] = (null != Request.QueryString["selType"]) ? Request.QueryString["selType"].ToString() : "";
                ViewState["sep"] = (null != Request.QueryString["sep"]) ? Request.QueryString["sep"].ToString() : "";
                initializePage();
            }
        }


        private void initializePage()
        {
            createTree();
            trvAccount.ExpandLevel = 1;
        }

        private void createRootNode(ref Microsoft.Web.UI.WebControls.TreeNode oRoot)
        {
            string sOrganName = "外部邮箱账号";

            oRoot.Text = sOrganName;
            oRoot.ImageUrl = "../images/toolbar/Folder_open.gif";
            oRoot.NavigateUrl = "";
            oRoot.Target = "";
            oRoot.ID = "0_0";
        }


        private void createTree()
        {
            /* c创建根节点 */
            Microsoft.Web.UI.WebControls.TreeNode oRoot = new Microsoft.Web.UI.WebControls.TreeNode();
            createRootNode(ref oRoot);
            trvAccount.Nodes.Add(oRoot);
            BindTree(oRoot);
        }

        /// <summary>
        /// 绑定树
        /// </summary>
        private void BindTree(Microsoft.Web.UI.WebControls.TreeNode node)
        {
            EmailBLL bll = new EmailBLL();
            LoginUser loginUser = Session["LogUserInfo"] as LoginUser;
            MsEmailAccount msAccount = new MsEmailAccount();
            msAccount.userId = loginUser.UserId;
            DataSet dSet = bll.GetAccountList(msAccount);
            DataView dv = new DataView(dSet.Tables[0]);

            AddTreeNodes(dv, node);//为树添加节点

            bll.Release();
            bll = null;
            msAccount = null;
        }

        /// <summary>
        /// 为树添加节点
        /// </summary>
        /// <param name="dv"></param>
        /// <param name="node"></param>
        private void AddTreeNodes(DataView dv, Microsoft.Web.UI.WebControls.TreeNode node)
        {
            string sParam = string.Empty;
            string encodeparam = string.Empty;
            string selType = ViewState["selType"].ToString().Trim();
            foreach (DataRowView dr in dv)
            {
                Microsoft.Web.UI.WebControls.TreeNode td = new Microsoft.Web.UI.WebControls.TreeNode();

                td.Text = dr["EML_A4_30"].ToString();
                td.ImageUrl = "../images/toolbar/bfiles.gif";
                //td.ExpandedImageUrl = "../images/toolbar/del_bq.gif";
                td.Target = "iFrmEdit";
                td.Type = "root";
                td.Text = dr["EML_A4_30"].ToString();
                td.ID = dr["EML_A4_10"].ToString();
                if (selType == "")
                {
                    sParam = "XH=" + dr["EML_A4_10"].ToString();
                    encodeparam = Base64Lib.Encode(sParam);
                    td.NavigateUrl = "email_wbyj_edit.aspx?" + encodeparam;
                }
                else
                {
                    td.CheckBox = true;
                    trSet.Style.Add(HtmlTextWriterStyle.Display, "block");
                }

                node.Nodes.Add(td);
            }
        }


        /// <summary>
        /// 删除ajax方法 删除WEB邮箱设置
        /// </summary>
        /// <returns></returns>
        [global::System.Web.Services.WebMethod]
        public static string DeleteAccount(string serExpr)
        {
            bool bFlag = false;
            MsEmailAccount msAccount = (MsEmailAccount)JavaScriptConvert.DeserializeObject(serExpr, typeof(MsEmailAccount));
            EmailBLL bll = new EmailBLL();
            bFlag = bll.DelAccount(msAccount);
            string sResult = (bFlag) ? "1" : "0";
            string operType = "Del";
            var newObj = new { operType = operType, resultSign = sResult, resultId = msAccount.Id };
            string resultSerExpr = JavaScriptConvert.SerializeObject(newObj);

            bll.Release();
            bll = null;
            newObj = null;
            msAccount = null;
            return resultSerExpr;

        }

        /// <summary>
        /// ajax方法 测试邮箱是否连接成功
        /// </summary>
        /// <returns></returns>
        [global::System.Web.Services.WebMethod]
        public static string TestAccount(string serExpr)
        {
            bool bFlag = false;
            MsEmailAccount msAccount = (MsEmailAccount)JavaScriptConvert.DeserializeObject(serExpr, typeof(MsEmailAccount));
            EmailBLL bll = new EmailBLL();
            msAccount = bll.GetAccount(msAccount);
            bFlag = Test(msAccount);
            string sResult = (bFlag) ? "1" : "0";
            string operType = "Test";
            var newObj = new {operType = operType, resultSign = sResult };
            string resultSerExpr = JavaScriptConvert.SerializeObject(newObj);
            bll.Release();
            bll = null;
            newObj = null;
            msAccount = null;
            return resultSerExpr;

        }
        
        /// <summary>
        /// ajax方法 接收邮件
        /// </summary>
        /// <returns></returns>
        [global::System.Web.Services.WebMethod]
        public static string ReciveEmail(string serExpr)
        {
            MsEmailAccount msAccount = (MsEmailAccount)JavaScriptConvert.DeserializeObject(serExpr, typeof(MsEmailAccount));
            EmailBLL bll = new EmailBLL();
            string sResult = bll.ReciveByJmail(msAccount);
            string operType = "Recive";
            var newObj = new { operType = operType, resultSign = sResult };
            string resultSerExpr = JavaScriptConvert.SerializeObject(newObj);
            bll.Release();
            bll = null;
            newObj = null;
            msAccount = null;
            return resultSerExpr;

        }

        public static bool Test(MsEmailAccount msAccount)
        {
            bool bFlag = false;
            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == false)
            {
                return false;
            }

            EmailLib emailObj = new EmailLib();
            emailObj.SenderEmail = msAccount.address;   //发件人的邮箱
            emailObj.Account = msAccount.pop3LogName;  //发件人邮箱账户
            emailObj.Password = msAccount.pop3Pass;   //发件人密码
            emailObj.ReceiveEmails = msAccount.address;  //收件人的邮箱，多个由分号隔开
            emailObj.MailSubject = "客户发送邮件";   //发送主题
            emailObj.Priority = System.Web.Mail.MailPriority.Low;  //发送优先级
            emailObj.MailContent = "客户的意见和建议,详细信息请看附件！";
            emailObj.MailFormat = System.Web.Mail.MailFormat.Text;  //发送格式，以文本形式发送
            emailObj.SMTPServer = msAccount.receiveSMTP;   //SMTP服务器

            List<string> lstSender = emailObj.Send();
            if (lstSender[0] == "1")
            {
                bFlag = true;
            }

            return bFlag;
        }

        protected void btGetValue_Click(object sender, EventArgs e)
        {
            string strRetId = string.Empty; 
            string strRetText = string.Empty;
            int Count = trvAccount.Nodes[0].Nodes.Count;
            for (int i = 0; i < Count; i++)
            {
                if (trvAccount.Nodes[0].Nodes[i].Checked == true)
                {
                    strRetId += trvAccount.Nodes[0].Nodes[i].ID;
                    strRetText += trvAccount.Nodes[0].Nodes[i].Text;
                    if (i != Count)
                    {
                        strRetId += ";";
                        strRetText += ";";
                    }
                }
            }

            string script = "<script language=javascript>";
            script += "window.opener.document.getElementById('" + ViewState["ctrlid"].ToString() + "').value = '" + strRetId + "';";
            script += "window.opener.document.getElementById('" + ViewState["ctrlname"].ToString() + "').value = '" + strRetText + "';";
            script += "window.opener.document.getElementById('" + ViewState["sep"].ToString() + "').value = '" + strRetText + "';";
            script += "self.close();";
            script += "</script>";
            Page.RegisterClientScriptBlock("test", script);
        }
    }
}
